package com.sy.filter;

import com.sy.annotation.PermissionAnnotation;
import com.sy.constant.BusinessConstant;
import com.sy.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Monkey-D-Gu
 * @version 1.0
 * @date 2020/9/11 0011 15:21
 * @usage 用来在每次请求的时候获取Cookie中的权限信息
 */
public class RoleHolder implements Filter {
    //当前线程中存放的登录角色信息
    private static ThreadLocal<PermissionAnnotation.Role> curRole = new ThreadLocal<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String roleStr = HttpUtils.getCookie(req, BusinessConstant.ROLE_POWER_COOKIE_KEY);
        if (StringUtils.equals(PermissionAnnotation.Role.ADMIN.toString(),roleStr)) {
            curRole.set(PermissionAnnotation.Role.ADMIN);
        } else if (StringUtils.equals(PermissionAnnotation.Role.TEACHER.toString(),roleStr)) {
            curRole.set(PermissionAnnotation.Role.TEACHER);
        } else if (StringUtils.equals(PermissionAnnotation.Role.STUDENT.toString(),roleStr)) {
            curRole.set(PermissionAnnotation.Role.STUDENT);
        }

        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }

    /**
     * 获取线程中的当前角色信息
     * @return 当前角色信息
     */
    public static PermissionAnnotation.Role getCurRole() {
        return curRole.get();
    }
}
